package com.ego.controller;

import com.ego.dao.LoginDao;
import com.ego.dao.impl.LoginDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 袁梦达 2019012364
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    private LoginDao loginDao = new LoginDaoImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        InputStream is = req.getInputStream();
        //读取客户端发送的字符串
        StringBuffer stringBuffer = new StringBuffer();
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = is.read(bytes)) != -1){
            stringBuffer.append(new String(bytes, 0, len));
        }

        String[] info = stringBuffer.toString().split(",");
        String userNumber = info[0];
        String password = info[1];

        if(loginDao.checkUser(userNumber, password)){
            //登录成功，保存登录状态，向客户端返回成功消息
            getServletContext().setAttribute("userNumber", userNumber);
            resp.getWriter().print(true);
        }else {
            //向客户端返回失败消息
            resp.getWriter().print(false);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
